package cn.dapeng.rpc.common.codec;

import cn.dapeng.rpc.common.Constant;
import cn.dapeng.rpc.common.PkmRequestMessage;
import cn.dapeng.rpc.common.RpcRequest;
import cn.dapeng.rpc.common.serial.SerializeFactory;
import cn.dapeng.rpc.common.util.MagicNumberUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ServerByteToMessageDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

        while (byteBuf.readableBytes() > 0) {
            int magicNum = byteBuf.getInt(byteBuf.readerIndex());
            if (!checkMagicValid(magicNum)) {
                System.out.println("客户端传递非法参数！");
                continue;
            }
            int serialType = MagicNumberUtil.getSerialVersion(magicNum);
            int bodyLen = MagicNumberUtil.getBodyLen(magicNum);

            if (byteBuf.readableBytes() >= (bodyLen + Integer.BYTES)) {
                byteBuf.readBytes(Integer.BYTES);
                byte[] body = new byte[bodyLen];
                byteBuf.readBytes(body);

                RpcRequest rpcRequest = SerializeFactory.deseria(body, RpcRequest.class, serialType);
                PkmRequestMessage obj = new PkmRequestMessage(magicNum, rpcRequest);
                list.add(obj);
            } else {
                break;
            }
        }
    }

    /**
     * 校验客户端参数的有效性
     *
     * @param num
     * @return
     */
    private boolean checkMagicValid(int num) {

        if (num <= 0) {
            return false;
        }

        int serialType = MagicNumberUtil.getSerialVersion(num);
        int version = MagicNumberUtil.getVersion(num);
        int requestType = MagicNumberUtil.getRequestType(num);

        if (version != Constant.VERSION || !(serialType == 0 || serialType == 1)) {

        }

        return true;
    }

}
